//
//  SQShowMessage.m
//  SQ_AProject
//
//  Created by 汪的一声就哭了！ on 16/3/26.
//  Copyright © 2016年 汪的一声就哭了！ All rights reserved.
//
#import "SQShowMessage.h"

@interface SQShowMessage()
@property (nonatomic, retain) UIView *backView;//背景
@property (nonatomic, retain) UILabel *messageLable;//提示内容
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation SQShowMessage

+ (SQShowMessage *)shareMessage
{
    static SQShowMessage *message = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        message = [[SQShowMessage alloc] init];
    });
    return message;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.backView = [[UIView alloc] init];
        _backView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
        self.messageLable = [[UILabel alloc] init];
        _messageLable.textColor = [UIColor whiteColor];
        _messageLable.font = [UIFont systemFontOfSize:17];
    }
    return self;
}
- (void)showMessageWithStr:(NSString *)str
{
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    CGSize r = [str sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}];
    if (r.width > app.window.frame.size.width-20) {
        CGRect rect = [str boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-100, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
        r = rect.size;
    }
    _backView.frame = CGRectMake((app.window.frame.size.width - r.width - 60) / 2, (app.window.frame.size.height - r.height - 20) / 2, r.width + 60, r.height + 20);
    _messageLable.frame = CGRectMake(30, 10, r.width, r.height);
    _messageLable.text = str;
    _messageLable.numberOfLines = 0;
    [_messageLable sizeToFit];
    _messageLable.textAlignment = NSTextAlignmentCenter;
    _backView.layer.cornerRadius = 10;
    [_backView addSubview:_messageLable];
    [app.window addSubview:_backView];
    //添加动画
//    [UIView animateWithDuration:2.5 animations:^{
//        _backView.frame = CGRectMake((app.window.frame.size.width - r.width - 60) / 2, (app.window.frame.size.height - r.height - 20) / 2-60 , r.width + 60, r.height + 20);
//    } completion:^(BOOL finished) {
//        [_backView removeFromSuperview];
//    }];
    if (_timer) {
        [_timer invalidate];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerAction:) userInfo:nil repeats:NO];
    } else {
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerAction:) userInfo:nil repeats:NO];
    }
}
- (void)timerAction:(NSTimer *)timer
{
    [_backView removeFromSuperview];
}
@end
